import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:go_router/go_router.dart';
import 'package:oktoast/oktoast.dart';
import 'package:provider/provider.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:wan_android/model/fav/fav_page_model.dart';
import 'package:wan_android/model/user/user_page_model.dart';

class FavPage extends StatefulWidget {
  const FavPage({super.key});

  @override
  State<FavPage> createState() => _FavPageState();
}

class _FavPageState extends State<FavPage> {
  final RefreshController _refreshController = RefreshController();
  late FavPageModel _favPageModel;
  late UserPageModel _userPageModel;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    FavPageModel favPageModel = Provider.of<FavPageModel>(context, listen: false);
    UserPageModel userPageModel = Provider.of<UserPageModel>(context, listen: false);
    
    if (userPageModel.userInfo != null) {
      favPageModel.getFavPageList(false);
    }

    setState(() {
      _favPageModel = favPageModel;
      _userPageModel = userPageModel;
    });
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    _refreshController.dispose();
  }

  Widget _renderFavList() {
    return Consumer<FavPageModel>(
      builder: (context, vm, child) {
        return ListView.builder(
          // physics: const NeverScrollableScrollPhysics(),
          itemCount: vm.favList.length,
          itemBuilder: (context, index) {
            // 滑动删除
            return Dismissible(
              key: Key('${vm.favList[index].id}'),
              direction: DismissDirection.endToStart,
              onDismissed: (direction) async {
                int id = vm.favList[index].id;
                await vm.cancelFavArticle(id);
                vm.removeFavOfPage(id);
                _userPageModel.removeFav(id);
                showToast(
                  '删除成功',
                  // duration: const Duration(seconds: 2),
                  backgroundColor: Colors.greenAccent,
                  position: ToastPosition.top,
                );
              },
              confirmDismiss: (direction) async {
                return await showCupertinoDialog(
                  context: context,
                  builder: (context) {
                    return CupertinoAlertDialog(
                      // title: Text('确认取消收藏'),
                      content: const Text('确认删除当前收藏?'),
                      actions: [
                        TextButton(
                          child: const Text('取消'),
                          onPressed:() {
                            return Navigator.of(context).pop(false);
                          },
                        ),
                        TextButton(
                          child: const Text('删除'),
                          onPressed:() {
                            return Navigator.of(context).pop(true);
                          },
                        ),
                      ],
                    );
                  },
                );
              },
              child: Container(
                width: double.infinity,
                padding: EdgeInsets.symmetric(vertical: 20.h, horizontal: 40.w),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Row(
                          children: [
                            const Icon(Icons.person),
                            Text(vm.favList[index].author),
                          ],
                        ),
                        // Text(date, style: const TextStyle(fontWeight: FontWeight.bold),)
                      ]
                    ),
                    
                    Padding(
                      padding: EdgeInsets.symmetric(vertical: 10.h, horizontal: 10.w),
                      child: Text(vm.favList[index].title),
                    ),

                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Row(
                          children: [
                            // Text(vm.favList[index].superChapterName.toString()),
                            Icon(Icons.circle, size: 10.sp,),
                            Text(vm.favList[index].chapterName),
                          ],
                        )
                      ],
                    )
                  ],
                ),
              )
            );
          },
        );
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    // 获取设备宽度和高度
    double deviceWidth = ScreenUtil().screenWidth;
    double deviceHeight = ScreenUtil().screenHeight;

    // 获取状态栏高度
    double statusBarHeight = MediaQuery.of(context).padding.top;

    // 获取 AppBar 高度
    double appBarHeight = kToolbarHeight;

    // 计算去除AppBar和状态栏后的高度
    double remainingHeight = deviceHeight - statusBarHeight - appBarHeight;

    return  SafeArea(
      top: false,
      child: Scaffold(
        appBar: AppBar(
          title: const Text('收藏', style: TextStyle(color: Colors.white),),
          centerTitle: true,
          backgroundColor: Colors.blueAccent,
        ),
        body: SmartRefresher(
          controller: _refreshController,
          enablePullDown: true,
          enablePullUp: true,
          header: const ClassicHeader(),
          footer: const ClassicFooter(),
          onRefresh: () async {
            await _favPageModel.getFavPageList(false);
            _refreshController.refreshCompleted();
          },
          onLoading: () async {
            await _favPageModel.getFavPageList(true);
            _refreshController.loadComplete();
          },

          child: Consumer<UserPageModel>(
            builder: (context, userVM, child) {
              if (userVM.userInfo != null) {
                return _renderFavList();
              }
              return SizedBox(
                width: double.infinity,
                height: remainingHeight.roundToDouble(),
                child: Center(
                  child: ElevatedButton(
                    child: const Text('立即登录'),
                    onPressed: () async {
                      final res = await context.push('/login');
                      if (res != null && res as bool) {
                        _favPageModel.getFavPageList(false);
                      }
                    },
                  ),
                )
              );
            },
          ),


          // child: SingleChildScrollView(
          //   child: Consumer<UserPageModel>(
          //     builder: (context, userVM, child) {
          //       if (userVM.userInfo != null) {
          //         return _renderFavList();
          //       }
          //       return SizedBox(
          //         width: double.infinity,
          //         // height: remainingHeight,
          //         child: Center(
          //           child: ElevatedButton(
          //             child: const Text('立即登录'),
          //             onPressed: () async {
          //               final res = await context.push('/login');
          //               if (res != null && res as bool) {
          //                 _favPageModel.getFavPageList(false);
          //               }
          //             },
          //           ),
          //         )
          //       );
          //     },
          //   )
          // ),
        )
      ),
    );
  }
}